package com.gzx.plugin.website.dict.service.impl;

import com.fhs.trans.service.impl.DictionaryTransService;
import com.gzx.plugin.website.dict.service.GzxDictService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;
import vip.xiaonuo.dev.feign.DevDictFeign;
import vip.xiaonuo.dev.feign.resp.DevDictResp;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zjt
 * @description
 * @date 2025/4/17 14:44
 */
@Service
@RequiredArgsConstructor
public class GzxDictServiceImpl implements GzxDictService, InitializingBean {

    private final DevDictFeign devDictFeign;

    private final DictionaryTransService dictionaryTransService;

    private static final String ROOT_PARENT_ID = "0";

    /**
     * 刷新字典缓存
     */
    @Override
    public void refreshDict() {
        // 异步不阻塞主线程，不会 增加启动用时
        Thread.startVirtualThread(() -> {
            // 使用redis能解决共享问题，但是性能没有直接取缓存的好。
            dictionaryTransService.makeUseRedis();
            List<DevDictResp> devDictList = devDictFeign.listAllDict();
            // 非root级别的字典根据ParentId分组
            Map<String, List<DevDictResp>> devDictGroupByPIDMap = devDictList.stream().filter(dict -> !ROOT_PARENT_ID
                    .equals(dict.getParentId())).collect(Collectors.groupingBy(DevDictResp::getParentId));
            Map<String, String> parentDictIdValMap = devDictList.stream().filter(dict -> ROOT_PARENT_ID
                    .equals(dict.getParentId())).collect(Collectors.toMap(DevDictResp::getId, DevDictResp::getDictValue));
            for (String parentId : parentDictIdValMap.keySet()) {
                if (devDictGroupByPIDMap.containsKey(parentId)) {
                    dictionaryTransService.refreshCache(parentDictIdValMap.get(parentId), devDictGroupByPIDMap.get(parentId).stream()
                            .collect(Collectors.toMap(DevDictResp::getDictValue, DevDictResp::getDictLabel)));
                }
            }
        });
    }

    @Override
    public void afterPropertiesSet() {
        refreshDict();
    }
}
